package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.Announcement;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.MomentsApi;
import com.tanhua.dubbo.server.api.UserApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class IMService {

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private UserApi userApi;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference(version = "1.0.0")
    private MomentsApi momentsApi;

    @Autowired
    private AnnouncementService announcementService;

    /**
     * 在消息模块中通过环信用户名查找用户信息
     *
     * @param username
     * @return
     */
    public UserInfoVo findUserByHuanXinId(String username) {
        HuanXinUser huanXinUser = huanXinApi.findUserByHuanXinUserName(username);
        if (!ObjectUtil.isNotEmpty(huanXinUser)) {
            return null;
        }
        UserInfo userInfo = userInfoService.findUserInfo(huanXinUser.getUserId());
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }
        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    /**
     * 添加好友
     *
     * @param friendId
     * @return
     */
    public Boolean addFriend(Long friendId) {
        User user = UserThreadLocal.get();

        String id = userApi.saveFriend(user.getId(), friendId);

        if (StrUtil.isNotEmpty(id)) {
            //注册好友关系到环信
            return huanXinApi.addFriend(user.getId(), friendId);
        }

        return false;
    }

    /**
     * 删除好友
     * @param friendId
     * @return
     */
    public void removeFriend(Long friendId){
        User user = UserThreadLocal.get();
        //删除好友关系
        boolean result = userApi.removeFriend(user.getId(), friendId);
        if(result){
            //删除环信好友关系
            huanXinApi.removeFriend(user.getId(),friendId);
        }
    }

    /**
     * 查看好友列表(包含搜索功能)
     *
     * @param page
     * @param pageSize
     * @param keyWord
     * @return
     */
    public PageResult findContactsList(Integer page, Integer pageSize, String keyWord) {
        //新建一个pageresult对象用于接收页面数据
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //从本地线程获取当前登录用户信息
        User user = UserThreadLocal.get();
        //该方法获取用户的所有好友的分页信息
        PageInfo<Users> users = userApi.findContactsList(user.getId(), page, pageSize, keyWord);
        //获取具体的用户数据集合
        List<Users> records = users.getRecords();
        //如果为空则当前用户没有好友
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        //获取用户集合中的用户ID封装到一个新的集合中
        List<Object> friendIds = CollUtil.getFieldValues(records, "friendId");
        //创建一个新的集合用于接收用户具体信息
        List<UserInfo> userInfoList;
        //通过用户ID查询所有好友的资料
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", friendIds);
        userInfoList = userInfoMapper.selectList(queryWrapper);
        //如果关键字不为空,则在查询中添加模糊查询的条件
        if (StrUtil.isNotEmpty(keyWord)) {
            List<Users> contactsList = userApi.findContactsList(user.getId());
            List<Object> friendId = CollUtil.getFieldValues(contactsList, "friendId");
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.in("user_id", friendId).like("nick_name", keyWord);
            //获取的是通过条件搜素获取的好友列表
            userInfoList = userInfoMapper.selectList(wrapper);
        }
        //新建一个UserVo集合用于封装返回页面的用户信息
        List<UsersVo> usersVoList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UsersVo usersVo = new UsersVo();
            usersVo.setId(userInfo.getUserId());
            usersVo.setAge(userInfo.getAge());
            usersVo.setAvatar(userInfo.getLogo());
            usersVo.setGender(userInfo.getSex().name().toLowerCase());
            usersVo.setNickname(userInfo.getNickName());
            //环信用户账号
            usersVo.setUserId("HX_" + String.valueOf(userInfo.getUserId()));
            usersVo.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));

            usersVoList.add(usersVo);
        }
        pageResult.setItems(usersVoList);
        return pageResult;
    }

    /**
     * 获取消息模块的点赞列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findLikeList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = momentsApi.findLikeList(user.getId(), page, pageSize);
        return fillCommentUserList(pageInfo);
    }

    /**
     * 获取消息模块的喜欢列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findLoveList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageInfo<Comment> loveList = momentsApi.findLoveList(user.getId(), page, pageSize);
        return fillCommentUserList(loveList);
    }

    /**
     * 消息模块获取评论列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findCommentList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageInfo<Comment> commentList = momentsApi.findCommentList(user.getId(), page, pageSize);
        return fillCommentUserList(commentList);
    }


    /**
     * 公共的用于填充评论者的用户信息的方法
     *
     * @param pageInfo
     * @return
     */
    private PageResult fillCommentUserList(PageInfo<Comment> pageInfo) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(pageInfo.getPageNum());
        pageResult.setPagesize(pageInfo.getPageSize());

        List<MessageCommentVo> messageCommentVoList = new ArrayList<>();

        List<Comment> records = pageInfo.getRecords();
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        //评论者的信息
        List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper);
        //List<UserInfo> userInfos = userInfoService.findUserInfoByUserIds(userIds);

        for (UserInfo userInfo : userInfos) {
            for (Comment record : records) {
                if (ObjectUtil.equals(userInfo.getUserId(), record.getUserId())) {
                    MessageCommentVo messageCommentVo = new MessageCommentVo();
                    messageCommentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "yyyy-MM-dd HH:mm"));//TODO
                    messageCommentVo.setId(record.getId().toHexString());
                    messageCommentVo.setNickname(userInfo.getNickName());
                    messageCommentVo.setAvatar(userInfo.getLogo());

                    messageCommentVoList.add(messageCommentVo);
                    break;
                }
            }
        }
        pageResult.setItems(messageCommentVoList);
        return pageResult;
    }

    /**
     * 消息模块公告列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findAnnouncementsList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        IPage<Announcement> announcementsList = announcementService.findAnnouncementsList(page, pageSize);
        if (ObjectUtil.isEmpty(announcementsList)) {
            return pageResult;
        }
        List<AnnouncementVo> announcementVoList = new ArrayList<>();
        List<Announcement> records = announcementsList.getRecords();
        for (Announcement record : records) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(record.getId().toString());
            announcementVo.setTitle(record.getTitle());
            announcementVo.setDescription(record.getDescription());
            announcementVo.setCreateDate(DateUtil.format(record.getCreated(), "yyyy-MM-dd HH:mm"));

            announcementVoList.add(announcementVo);
        }
        pageResult.setItems(announcementVoList);
        return pageResult;
    }
}
